//
// Created by 郝羽 on 2017/12/15.
//

#ifndef RTC_XSWITCH2_NORM_DIST_HPP
#define RTC_XSWITCH2_NORM_DIST_HPP

#include <random>

namespace test {
    class NormDist {
    public:
        NormDist(double mean, double stddev) : dist_(mean, stddev) {};

        double Random() {
            return dist_(gen_);
        };

    private:
        std::random_device rd_;
        std::mt19937 gen_;
        std::normal_distribution<double> dist_;
    };

    class UniformDist {
    public:
        UniformDist(int min, int max) : dist_(min, max) {};

        double Random() {
            return dist_(gen_);
        };

        std::random_device rd_;
        std::mt19937 gen_;
        std::uniform_int_distribution<int> dist_;
    };

    class GoogleRandom {
    public:
        GoogleRandom(uint64_t seed) : state_(seed) {};
        double Gaussian(double mean, double std_dev) {
            // Creating a Normal distribution variable from two independent uniform
            // variables based on the Box-Muller transform, which is defined on the
            // interval (0, 1]. Note that we rely on NextOutput to generate integers
            // in the range [1, 2^64-1]. Normally this behavior is a bit frustrating,
            // but here it is exactly what we need.
            const double kPi = 3.14159265358979323846;
            double u1 = static_cast<double>(NextOutput()) / 0xFFFFFFFFFFFFFFFFull;
            double u2 = static_cast<double>(NextOutput()) / 0xFFFFFFFFFFFFFFFFull;
            return mean + std_dev * sqrt(-2 * log(u1)) * cos(2 * kPi * u2);
        };

        int32_t Rand(int32_t low, int32_t high) {
            const int64_t low_i64{low};
            return static_cast<int32_t>(
                    Rand(static_cast<uint32_t>(high - low_i64)) + low_i64);
        };

        uint32_t Rand(uint32_t t) {
            // Casting the output to 32 bits will give an almost uniform number.
            // Pr[x=0] = (2^32-1) / (2^64-1)
            // Pr[x=k] = 2^32 / (2^64-1) for k!=0
            // Uniform would be Pr[x=k] = 2^32 / 2^64 for all 32-bit integers k.
            uint32_t x = NextOutput();
            // If x / 2^32 is uniform on [0,1), then x / 2^32 * (t+1) is uniform on
            // the interval [0,t+1), so the integer part is uniform on [0,t].
            uint64_t result = x * (static_cast<uint64_t>(t) + 1);
            result >>= 32;
            return result;
        };

        uint64_t NextOutput() {
            state_ ^= state_ >> 12;
            state_ ^= state_ << 25;
            state_ ^= state_ >> 27;
            return state_ * 2685821657736338717ull;
        }

    private:
        uint64_t state_;
    };
}

#endif //RTC_XSWITCH2_NORM_DIST_HPP
